package com.ifonly.security;

import com.ifonly.config.Configuration;
import com.ifonly.logger.Logger;
import com.ifonly.utils.CryptoUtils;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-31 14:28
 * @since JDK 1.6
 */
public abstract class AbstractAppShiroRealm extends AuthorizingRealm {
    protected Configuration cfg = Configuration.getInstance();
    protected Logger logger;

    public AbstractAppShiroRealm() {
        this.logger = Logger.getLogger(AbstractAppShiroRealm.class);
    }

    @Override
    public String getName() {
        return "AbstractAppShiroRealm";
    }

    public void initialize () {
        // default do nothing
        HashedCredentialsMatcher matcher;

        if (cfg.isSecurity() && cfg.isSecurityRetryLimit()) {
            matcher = new RetryLimitHashedCredentialsMatcher();
        } else {
            matcher = new HashedCredentialsMatcher();
        }
        matcher.setHashAlgorithmName(CryptoUtils.HASH_ALGORITHM);
        matcher.setHashIterations(CryptoUtils.HASH_INTERATIONS);
        setCredentialsMatcher(matcher);
    }

    @Override
    public void onLogout(PrincipalCollection principals) {
        clearCache(principals);
    }

    @Override
    protected void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }
}
